<template>
  <div class="rule-select-body">
    <el-dialog
      v-model="modalVisible"
      title="接口列表"
      width="1000px"
      align-center
      :before-close="close"
      top="100px"
    >
    <div class="mt10 mb10 flex" >
      <el-input placeholder="搜索名称" v-model="search_value" />
    </div>
      <div class="rules-list">
        <template v-for="(item, index) in ruleLists" :key="index">
          <div class="rules-item"  v-if="search_value == '' || item.search === true" @click="selectItem(item)">
            <div>接口名称：{{ item.title }}</div>
            <div>请求方式：{{ item.method }}</div>
            <div>接口地址：{{ item.rule }}</div>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name: "select-rule-modal",
};
</script>
<script setup lang="ts">
import { ref, getCurrentInstance ,watch} from "vue";
import { getRuleList } from "@/api/system/menus";
import { Result, ResultError } from "@/types";

const {
  proxy: { $message },
} = getCurrentInstance() as any;

const emit = defineEmits(["change"]);

const modalStatus = ref<boolean>(false);
const modalVisible = ref<boolean>(false);
const loadMessage = ref();

const open = () => {
  if (modalStatus.value == true) {
    return;
  }
  modalStatus.value = true;
  loadMessage.value = $message({
    duration: 0,
    message: "正在加载路由接口...",
  });
  setTimeout(() => {
    initData();
  }, 1000);
};

const ruleLists = ref<any>([]);

const initData = () => {
  search_value.value = '';
  getRuleList()
    .then((res: Result) => {
      modalVisible.value = true;
      ruleLists.value = res.data;
      loadMessage.value.close();
    })
    .catch((err:ResultError) => {
      loadMessage.value.close();
      if (err.message && typeof err.message == "string") {
        $message.error(err.message);
      }
    });
};

const search_value = ref<string>('')

const close = () => {
  modalStatus.value = false;
  modalVisible.value = false;
  search_value.value = '';
};

const selectItem = (item: any) => {
  emit("change", item);
  modalVisible.value = false;
  modalStatus.value = false;
};

watch(
  () => search_value.value,
  (val) => {
    ruleLists.value?.forEach((item: any) => {
      item.search = item.rule.indexOf(val) !== -1 || item.title.indexOf(val) !== -1 ? true : false;
    });
  }
);

defineExpose({ open });
</script>
<style >
.rule-select-body .el-dialog__body{
  padding: 0 20px 20px 20px;
}
.rule-select-body .rules-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  max-height: 600px;
  overflow: hidden;
  overflow-y: scroll;
}
.rule-select-body .rules-item {
  width: calc(33.33% - 34px);
  margin: 5px;
  background: #f0f0f0;
  border-radius: 5px;
  padding: 10px;
  border: 2px solid #f0f0f0;
  cursor: pointer;
}
.rule-select-body .rules-item:hover {
  border-color: var(--base-default);
}
</style>